import json
import pandas as pd
import os


def generate_medical_kg_report(json_str: str, output_prefix: str = "病例"):
    """
    根据 LLM 返回的死亡因果链 JSON 字符串，生成结构化表格与 HTML 可视化报告。

    参数:
        json_str (str): 清理后的纯 JSON 字符串（不含 ```json...```）
        output_prefix (str): 输出文件前缀，如 "519038_张三"

    输出:
        - 打印三个表格到控制台
        - 保存 HTML 报告为 "{output_prefix}_知识图谱.html"
    """
    try:
        data = json.loads(json_str)
    except json.JSONDecodeError as e:
        print(f"❌ JSON 解析失败: {e}")
        print("原始内容预览:", json_str[:200])
        return

    # 提取三部分数据
    df_chain = pd.DataFrame(data.get('death_causality_chain', []))
    df_triplets = pd.DataFrame(data.get('causality_triplets', []))
    df_nodes = pd.DataFrame(data.get('knowledge_graph_nodes', []))

    # 打印表格
    print("【死亡因果链】")
    print(df_chain if not df_chain.empty else "无数据")
    print("\n【因果三元组】")
    print(df_triplets if not df_triplets.empty else "无数据")
    print("\n【知识图谱节点】")
    print(df_nodes if not df_nodes.empty else "无数据")

    # 构建 HTML 模板
    html_template = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医学死亡因果链知识图谱</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {{ font-family: 'Segoe UI', sans-serif; margin: 2rem; }}
        table {{ width: 100%; margin-bottom: 2rem; border-collapse: collapse; }}
        th, td {{ border: 1px solid #ddd; padding: 0.75rem; text-align: left; }}
        th {{ background-color: #f3f4f6; }}
        h1, h2 {{ color: #1e3a8a; margin-top: 1.5rem; }}
        #graph-container {{ height: 500px; margin-top: 2rem; border: 1px solid #eee; border-radius: 0.5rem; }}
    </style>
</head>
<body>
    <div class="container mx-auto">
        <h1 class="text-2xl font-bold">医学死亡因果链知识图谱</h1>

        <h2 class="text-xl font-semibold mt-6">死亡因果链</h2>
        {chain_table}

        <h2 class="text-xl font-semibold mt-6">因果三元组</h2>
        {triplets_table}

        <h2 class="text-xl font-semibold mt-6">知识图谱节点</h2>
        {nodes_table}

        <div id="graph-container" class="mt-8"></div>
    </div>

    <script>
        // TODO: 可在此处添加 D3.js 知识图谱渲染逻辑
        console.log("知识图谱数据待实现");
    </script>
</body>
</html>
'''

    # 生成表格 HTML（若为空则显示提示）
    chain_table = df_chain.to_html(index=False, escape=False,
                                   classes="min-w-full") if not df_chain.empty else "<p>无死亡因果链数据</p>"
    triplets_table = df_triplets.to_html(index=False, escape=False,
                                         classes="min-w-full") if not df_triplets.empty else "<p>无因果三元组数据</p>"
    nodes_table = df_nodes.to_html(index=False, escape=False,
                                   classes="min-w-full") if not df_nodes.empty else "<p>无知识图谱节点数据</p>"

    # 填充模板
    final_html = html_template.format(
        chain_table=chain_table,
        triplets_table=triplets_table,
        nodes_table=nodes_table
    )

    # 保存 HTML 文件
    html_filename = f"{output_prefix}_知识图谱.html"
    with open(html_filename, "w", encoding="utf-8") as f:
        f.write(final_html)

    print(f"\n✅ HTML 报告已保存为: {os.path.abspath(html_filename)}")